package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;

import com.sky.result.PageResult;
import com.sky.service.IOrderDetailService;
import com.sky.service.IOrdersService;
import com.sky.service.IShoppingCartService;
import com.sky.service.WebSocketServer;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-05-18
 */
@Service

@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {


    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrdersMapper orderMapper;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private IShoppingCartService shoppingCartService;

    @Autowired
    private WebSocketServer webSocketServer;


    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        //1.先看收货地址是否为空，为空就抛异常
        AddressBook addressBook = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            // 收货地址为空，抛出异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

//2.查询当前用户的购物车数据，如果为空就抛异常
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectList(wrapper);
        if (shoppingCartList.isEmpty()) {
            // 购物车数据为空，抛出异常
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //3.构建订单数据
        Orders orders = new Orders();

        BeanUtil.copyProperties(ordersSubmitDTO, orders);
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//生成订单号
        orders.setUserId(userId);
        orders.setStatus(orders.PENDING_PAYMENT);//待付款
        orders.setPayStatus(orders.UN_PAID);//未支付
        orders.setOrderTime(new Date());
        orders.setAddress(addressBook.getDetail());

        //4.向订单表里插入订单数据
        ordersMapper.insert(orders);

        //5.向订单详情表里插入数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtil.copyProperties(shoppingCart, orderDetail);
            //设置订单id（因为orderDetail表里独有字段）
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }


        //批量插入数据
        orderDetailService.saveBatch(orderDetailList);
        //6.清空购物车
        LambdaQueryWrapper<ShoppingCart> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(ShoppingCart::getUserId, userId);
        shoppingCartMapper.delete(wrapper1);
        //7.返回订单数据
        OrderSubmitVO orderSubmitVO = OrderSubmitVO
                .builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount()).orderTime(orders.getOrderTime()).build();

        return orderSubmitVO;
    }


    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())//订单id
                .status(Orders.TO_BE_CONFIRMED)//待确认
                .payStatus(Orders.PAID)//已支付
                .checkoutTime(new Date())//结账时间
                .build();

        orderMapper.update(orders);//更新订单状态

        Map map = new HashMap();
        map.put("type", 1);//消息类型，1代表来单提示
        map.put("orderId", ordersDB.getId());//订单id
        map.put("content", "订单号:" + outTradeNo);
        //通过webSoket实现来单提示，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    @Override
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {


        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();

        ordersPageQueryDTO.setStatus(status);
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        // 1.创建分页对象
        Page<Orders> p = new Page<>(pageNum, pageSize);
        //2.条件分页查询
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ordersPageQueryDTO.getUserId() != null, Orders::getUserId, ordersPageQueryDTO.getUserId())
                .eq(ordersPageQueryDTO.getStatus() != null, Orders::getStatus, ordersPageQueryDTO.getStatus())
                .ge(ordersPageQueryDTO.getBeginTime() != null, Orders::getOrderTime, ordersPageQueryDTO.getBeginTime())
                .le(ordersPageQueryDTO.getEndTime() != null, Orders::getOrderTime, ordersPageQueryDTO.getEndTime())
                .like(ordersPageQueryDTO.getNumber() != null && !ordersPageQueryDTO.getNumber().isEmpty(), Orders::getNumber, ordersPageQueryDTO.getNumber())
                .like(ordersPageQueryDTO.getPhone() != null && !ordersPageQueryDTO.getPhone().isEmpty(), Orders::getPhone, ordersPageQueryDTO.getPhone())
                .orderByDesc(Orders::getOrderTime);


        //3.调用mapper层执行查询
        Page<Orders> ordersPage = orderMapper.pageQuery(p, wrapper);
        ArrayList<OrderVO> orderVOArrayList = new ArrayList<>();
        //4.查询订单详细├─ orderDetailList
        if (ordersPage.getTotal() > 0 && ordersPage != null) {
            List<Orders> ordersList = ordersPage.getRecords();

            for (Orders orders : ordersList) {
                // 根据订单id查询订单详情
                LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(OrderDetail::getOrderId, orders.getId());
                List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
                //5.封装vo
                OrderVO orderVO = new OrderVO();
                BeanUtil.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                orderVOArrayList.add(orderVO);
            }
        }

        //6.封装分页结果
        return new PageResult(p.getTotal(), orderVOArrayList);


    }

    /**
     * 用户取消订单
     *
     * @return
     */
    @Override
    public void userCancelById(Long id) {
        /*
        业务规则：
        - 待支付和待接单状态下，用户可直接取消订单
        - 商家已接单状态下，用户取消订单需电话沟通商家
        - 派送中状态下，用户取消订单需电话沟通商家
        - 如果在待接单状态下取消订单，需要给用户退款
        - 取消订单后需要将订单状态修改为“已取消”
         */

        //1.根据订单id查询订单
        Orders ordersDB = orderMapper.selectById(id);
        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);//订单不存在，抛出异常
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        //待支付和待接单状态下，用户可直接取消订单
        if (ordersDB.getStatus() > 2) { //不是1待付款 2待接单直接抛异常
            // 订单状态不对，抛出异常
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 订单处于待接单状态下取消，需要进行退款
        //如果在待接单状态下取消订单，需要给用户退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {//待接单状态
            //调用微信支付退款接口
            log.info("调用微信支付退款接口");//此时微信支付没有完成
        }
        //订单支付状态修改为 退款
        orders.setPayStatus(Orders.REFUND);//退款
        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);//订单已经取消
        orders.setCancelReason("用户取消");//取消原因
        orders.setCancelTime(new Date());//取消时间
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {

        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();
        // 根据订单id查询订单详情
        LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(OrderDetail::getOrderId, id);
        // 查询订单详情
        List<OrderDetail> orderDetailsDB = orderDetailMapper.selectList(wrapper1);
        if (orderDetailsDB == null || orderDetailsDB.isEmpty()) {
            // 订单不存在，抛出异常
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailsDB) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtil.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setId(null); // 显式设置ID为null

            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(new Date());
            shoppingCartList.add(shoppingCart);
        }
        // 将购物车对象批量添加到数据库
        shoppingCartService.saveBatch(shoppingCartList);

    }

    /*
    - 输入订单号/手机号进行搜索，支持模糊搜索
    - 根据订单状态进行筛选
    - 下单时间进行时间筛选
    - 搜索内容为空，提示未找到相关订单
    - 搜索结果页，展示包含搜索关键词的内容
    - 分页展示搜索到的订单数据
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //1.设置分页参数
        int page = ordersPageQueryDTO.getPage();
        int pageSize = ordersPageQueryDTO.getPageSize();
        //2.创建分页对象
        Page<Orders> p = new Page<>(page, pageSize);

        //3.创建分页条件
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ordersPageQueryDTO.getUserId() != null, Orders::getUserId, ordersPageQueryDTO.getUserId())
                .eq(ordersPageQueryDTO.getStatus() != null, Orders::getStatus, ordersPageQueryDTO.getStatus())
                .ge(ordersPageQueryDTO.getBeginTime() != null, Orders::getOrderTime, ordersPageQueryDTO.getBeginTime())
                .le(ordersPageQueryDTO.getEndTime() != null, Orders::getOrderTime, ordersPageQueryDTO.getEndTime())
                .like(ordersPageQueryDTO.getNumber() != null && !ordersPageQueryDTO.getNumber().isEmpty(), Orders::getNumber, ordersPageQueryDTO.getNumber())
                .like(ordersPageQueryDTO.getPhone() != null && !ordersPageQueryDTO.getPhone().isEmpty(), Orders::getPhone, ordersPageQueryDTO.getPhone())
                .orderByDesc(Orders::getOrderTime);
        //4.执行分页查询
        Page<Orders> pagedQuery = orderMapper.pageQuery(p,
                wrapper);
        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = new ArrayList<>();
        List<Orders> ordersList = pagedQuery.getRecords();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                OrderVO orderVO = new OrderVO();
                // 将共同字段复制到OrderVO
                BeanUtil.copyProperties(orders, orderVO);

                //根据订单id获取菜品信息字符串
                String orderDishes = getOrderDishesStr(orders);
                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
                //此时vo不需要orderDetailList，只需要orderDishes即可

            }
        }
        return new PageResult(p.getTotal(), orderVOList);

    }


    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        // 根据订单id查询订单菜品详情信息
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getOrderId, orders.getId());
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper);
        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);


    }

    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        //1.查询待接单数量
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getStatus, Orders.TO_BE_CONFIRMED);//待接单状态
        Integer toBeConfirmed = Math.toIntExact(orderMapper.selectCount(wrapper));
        //2.待派送数量

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        // private Integer status;
        LambdaQueryWrapper<Orders> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Orders::getStatus, Orders.CONFIRMED);
        Integer confirmed = Math.toIntExact(orderMapper.selectCount(wrapper1));
//        派送中数量
        LambdaQueryWrapper<Orders> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(Orders::getStatus, Orders.DELIVERY_IN_PROGRESS);
        Integer deliveryInProgress = Math.toIntExact(orderMapper.selectCount(wrapper2));
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);


        return orderStatisticsVO;
    }

    @Override
    public OrderVO details(Long id) {
    /*    - 订单详情页面需要展示订单基本信息（状态、订单号、下单时间、收货人、电话、收货地址、金额等）
        - 订单详情页面需要展示订单明细数据（商品名称、数量、单价）*/

        //1.根据订单id查询订单基本信息
        Orders orders = orderMapper.selectById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtil.copyProperties(orders, orderVO);
        //2.解决订单详情
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getOrderId, id);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper);
        orderVO.setOrderDetailList(orderDetailList);
        // 解决订单菜品信息
        String orderDishes = getOrderDishesStr(orders);
        orderVO.setOrderDishes(orderDishes);
        return orderVO;

    }


    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.selectById(ordersRejectionDTO.getId());
        /*
           //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
           private Integer status;
         */

        //订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //抛出异常订单状态错误
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //支付状态 0未支付 1已支付 2退款
//        拒单需要退款
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {//如果已经支付则要退款
            //用户已支付，需要退款
            log.info("申请退款：");
        }

        // ，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())//订单id
                .status(Orders.CANCELLED)//订单状态改为已取消
                .cancelTime(new Date())//取消时间
                .rejectionReason(ordersRejectionDTO.getRejectionReason())//拒单原因
                .build();
        orderMapper.update(orders);

    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        /*
        - 取消订单其实就是将订单状态修改为“已取消”
        - 商家取消订单时需要指定取消原因
        - 商家取消订单时，如果用户已经完成了支付，需要为用户退款
         */

        // 根据id查询订单
        Orders ordersDB = orderMapper.selectById(ordersCancelDTO.getId());
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        //支付状态 0未支付 1已支付 2退款
        Integer payStatus = ordersDB.getPayStatus();//支付状态
        if (payStatus == Orders.PAID) {//用户已支付，需要退款
            log.info("申请退款：");
        }

        //取消订单其实就是将订单状态修改为“已取消”      // 商家取消订单时需要指定取消原因
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())//订单id
                .status(Orders.CANCELLED)//订单状态改为已取消
                .cancelTime(new Date())//取消时间
                .cancelReason(ordersCancelDTO.getCancelReason())//拒单原因
                .build();
        orderMapper.update(orders);

    }

    @Override
    public void delivery(Long id) {
        /**
         * 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
         */
        //1.根据id查询订单
        Orders orders = orderMapper.selectById(id);
        //2.判断订单状态是否为已接单
        if (orders == null || !Orders.CONFIRMED.equals(orders.getStatus())) {
            throw new OrderBusinessException("订单不存在或不是已接单状态");
        }
        //3.修改订单状态为派送中
        Orders updateOrder = Orders.builder()
                .id(id)//订单id
                .status(Orders.DELIVERY_IN_PROGRESS)//派送中
                .build();
        orderMapper.update(updateOrder);
    }

    @Override
    public void complete(Long id) {
        /**
         * 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
         */
        //1.根据id查询订单
        Orders orders = orderMapper.selectById(id);
        //2.判断订单状态是否为已接单
        if (orders == null || !Orders.DELIVERY_IN_PROGRESS.equals(orders.getStatus())) {
            throw new OrderBusinessException("订单不存在或不是派送中状态");
        }
        //3.修改订单状态为派送中
        Orders updateOrder = Orders.builder()
                .id(id)//订单id
                .status(Orders.COMPLETED)//已完成
                .build();
        orderMapper.update(updateOrder);
    }

    @Override
    public void reminder(Long id) {
        //1.根据id查询订单
        Orders orders = orderMapper.selectById(id);
        //2.订单不存在就抛异常
        if (orders == null) {
            throw new OrderBusinessException("订单不存在");
        }
        //3.修改订单状态
        Orders build = Orders.builder()
                .id(id)
                .remark("用户催单")
                .build();
        orderMapper.updateById(build);


        //4.发送短信提醒
        HashMap map = new HashMap();
        map.put("type", 2);//2表示催单
        map.put("orderId", id);
        map.put("content", "订单号:" + orders.getNumber() + "用户催单，请注意及时配送！");
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


}


